<?php if(!defined('BASEPATH')) exit('No direct script access allowed');

class League extends CI_Controller
{
    protected $sesja= null;
    protected $log  = null;
    protected $elems= null;
    
    public function __construct() 
    {
        parent::__construct();
        $this->load->model('League_model','liga');
        $this->sesja= $this->session->userdata('sesja');
        $this->log  = new Logevent();
        $this->elems= new Elements();
    }
    
    /*
     * Pokazuje dostępne ligi dzieląc je względem miast i rozgrywek
     * 
     * @return mixed
     */
    public function show_leagues()
    {
        $res = $this->liga->get_leagues();
        $this->log->log_event($this->sesja,$res['stan']);
        if($res['stan'])
        {
            $cont['show']   = $res['wynik'];
            $head['h1']     = 'Ligi';
            $this->elems->load_view($this->sesja,'league/show_leagues',$cont,$head);
        }
        else
            $this->elems->load_alert($this->sesja,'alert','Brak dodanych lig w systemie',anchor('league/add_league','Dodaj ligę'));        
    }
    
    /*
     * Wyświetla tabelę, statystyki i terminarz meczy z danej ligi
     * 
     * @param int $id       - id ligi
     * @param int $season   - sezon (rok)
     * @return mixed
     */
    public function show_league($id)
    {
        //$this->output->cache(5);
        $teams = $this->liga->get_league_table($id);
        $this->log->log_event($this->sesja,$teams['stan']);
        $score = $this->liga->get_fixtures($id);
        $this->log->log_event($this->sesja,$score['stan']);
        if($teams['stan'] && $score['stan'])
        {
            foreach($teams['wynik']['comp'] as $wynik)
                foreach($wynik['league'] as $w)
                {
                    $head['h1']     = $wynik['code'].' '.$w['sezon'].' - '.$w['code'];
                    $cont['sezon']  = $w['sezon'];
                    break;
                }
            $cont['teams']  = $teams['wynik'];
            $cont['score']  = $score['wynik'];
            if($this->sesja['editor']==1)
                $cont['editor'] = TRUE;
            $foot['js']     = array(
                'js/libs/tablesorter.js',
                'js/team/show_team.js'
            );
            $this->elems->load_view($this->sesja,'league/show_league',$cont,$head,$foot);
        }
        elseif(!$teams['stan'])
            $this->elems->load_alert($this->sesja,'alert','Brak rozegranych meczy'); 
        elseif(!$score['stan'])
            $this->elems->load_alert($this->sesja,'alert','Brak meczy w terminarzu');
    }
    
    public function show_tables()
    {
        $head['h1']     = 'Tabele ligowe';
        $tables         = $this->liga->get_league_tables();
        $this->log->log_event($this->sesja,$tables['stan']);
        if($tables['stan'])
        {
            $cont['tables'] = $tables['wynik'];
            $this->elems->load_view($this->sesja,'league/show_tables',$cont,$head);
        }
        else
            $this->elems->load_alert($this->sesja,'alert','Brak tabel z obecnego sezonu');
    }
    
    /*
     * Wyświetla formularz dodawania ligi
     * 
     * @return mixed
     */
    public function add_league()
    {
        if(isset($this->sesja['id']) && $this->sesja['admin']==1)
        {
            $head['h1']     = 'Dodaj nową ligę';
            $comps          = $this->liga->get_comps();
            $this->log->log_event($this->sesja,$comps['stan']);
            if($comps['stan'])
                $cont['comps']  = $comps['wynik'];
            else
                $this->elems->load_alert(
                        $this->sesja,
                        'alert',
                        'Brak dostępnych rozgrywek.<br/>Należy dodać rozgrywki najpierw, a potem ligę.',
                        anchor('league/add_comp','Powrót do poprzedniej strony')
                );
            $this->elems->load_view($this->sesja,'league/add_league',$cont,$head);
        }
        else
            $this->elems->load_alert($this->sesja,'error','Nie masz uprawnień do korzystania z tej strony');
    }
    
    public function add_fixture()
    {
        if(isset($this->sesja['id']) && $this->sesja['editor']==1)
        {
            $head['h1'] = 'Dodaj kolejkę ligową';
            $ligi = $this->liga->get_select_leagues($this->config->item('ut_comp'),1);
            $this->log->log_event($this->sesja,$ligi['stan']);
            if($ligi['stan'])
            {
                $cont['ligi'] = $ligi['wynik'];
                $cont['sezony']= $this->liga->get_seasons();
                $this->load->model('Team_model');
                $teams = $this->Team_model->get_select_teams(0,$this->config->item('ut_liga'));
                $this->log->log_event($this->sesja,$teams['stan']);
                if($teams['stan'])
                {
                    $cont['teams']  = $teams['wynik'];
                    $foot['js']     = array(
                        'js/league/add_fixture.js',
                        'js/default/datepicker.js'
                        );
                    $this->elems->load_view($this->sesja,'league/add_fixture',$cont,$head,$foot);
                }
                else
                    $this->elems->load_alert($this->sesja,'alert','Nie ma drużyn w lidze',anchor('team/add_team','Dodaj drużynę'));
            }
            else
                $this->elems->load_alert($this->sesja,'alert','Nie ma dostepnych lig',anchor('league/add_league','Dodaj ligę'));
        }
        else
            $this->elems->load_alert($this->sesja,'error','Nie masz uprawnień do korzystania z tej strony');
    }
    
    /*
     * Wyświetla formularz dodawania rozgrywek
     * 
     * @return mixed
     */
    public function add_comp()
    {
        if(isset($this->sesja['id']) && $this->sesja['admin']==1)
        {
            $head['h1']     = 'Dodaj nowe rozgrywki';
            $miasta         = $this->liga->get_cities();
            $this->log->log_event($this->sesja,$miasta['stan']);
            if($miasta['stan'])
                $cont['miasta'] = $miasta['wynik'];
            else
                $cont['miasta'] = '';
            $this->elems->load_view($this->sesja,'league/add_comp',$cont,$head);
        }
        else
            $this->elems->load_alert($this->sesja,'error','Nie masz uprawnień do korzystania z tej strony');
    }
    
    /*
     * Dodawanie rozgrywek do bazy danych po wykonaniu walidacji wartości pól
     * 
     * @return mixed
     */
    public function insert_comp()
    {
        if(isset($this->sesja['id']) && $this->sesja['editor']==1)
        {
            if(isset($_POST['add_comp']))
            {
                $this->load->library('form_validation');
                $this->form_validation->set_error_delimiters('<p class="error">','</p>');
                $this->form_validation->set_rules('comp_name','Nazwa rozgrywek','required|xss_clean');
                $this->form_validation->set_rules('comp_code','skrócona nazwa rozgrywek','required|max_length[10]|xss_clean');
                if($this->input->post('city')=='lista')
                    $this->form_validation->set_rules('lcity','Miasto','required|xss_clean');
                else
                    $this->form_validation->set_rules('icity','Miasto','required|xss_clean');

                if($this->form_validation->run() == FALSE && isset($_POST['add_comp']))
                    $this->add_comp();
                elseif($this->form_validation->run() == FALSE && isset($_POST['edit_comp']))
                    $this->edit_comp($this->input->post('cid'));
                else
                {
                    if($this->input->post('city')=='lista')
                        $tab['comp_city'] = $this->input->post('lcity');
                    else
                    {
                        $state = $this->liga->check_city($this->input->post('icity'));
                        $this->log->log_event($this->sesja,$state);
                        if($state)
                        {
                            $this->elems->load_alert(
                                    $this->sesja,
                                    'error',
                                    'Miasto o nazwie: '.$this->input->post('icity').' już istnieje.',
                                    get_back_link()
                            );
                        }
                        else
                        {
                            $c['city_name'] = $this->input->post('icity');
                            $city = $this->liga->insert_city($c);
                            $this->log->log_event($this->sesja,$city['stan']);
                            if($city['stan'])
                                $tab['comp_city'] = $city['id'];
                            else
                                $this->elems->load_alert(
                                        $this->sesja,
                                        'error',
                                        'Wystąpił bląd podczas dodawania: '.$this->input->post('icity').' do bazy danych.<br/>MySQL: '.$this->db->last_query(),
                                        get_back_link()
                                );
                        }                        
                    }
                    $tab['comp_name'] = $this->input->post('comp_name');
                    $tab['comp_code'] = $this->input->post('comp_code');
                    $wynik = $this->liga->insert_comp($tab);
                    $this->log->log_event($this->sesja,$wynik);
                    if($wynik)
                        $this->elems->load_alert($this->sesja,'success','Dodano rozgrywki do bazy danych.');
                    else
                        $this->elems->load_alert(
                                $this->sesja,
                                'error',
                                'Wystąpił błąd podczas dodawania rozgrywek do bazy danych<br/>MySQL: '.$this->db->last_query(),
                                get_back_link()
                        );
                }
                
            }
            else
                $this->elems->load_alert($this->sesja,'error','Nie masz uprawnień do korzystania z tej strony');
        }
        else
            $this->elems->load_alert($this->sesja,'error','Nie masz uprawnień do korzystania z tej strony');
    }
    
    /*
     * Dodawanie ligi do bazy danych po wykonaniu walidacji wartości pól
     * 
     * @return mixed
     */
    public function insert_league()
    {
        if(isset($this->sesja['id']) && $this->sesja['editor']==1)
        {
            pretty_print($_POST);
        }
        else
            $this->elems->load_alert($this->sesja,'error','Nie masz uprawnień do korzystania z tej strony');
    }
    
    public function insert_fixture()
    {
        if(isset($this->sesja['id']) && $this->sesja['editor']==1)
        {
            $ggp = $this->input->post('gosp-gol');
            $ggc = $this->input->post('gosc-gol');
            
            $this->load->library('form_validation');
            $this->form_validation->set_error_delimiters('<p class="error">','</p>');
            $this->form_validation->set_rules('fixt_date','Data kolejki','required|xss_clean');
            if($this->input->post('add_fixture'))
            {
                $this->form_validation->set_rules('fixt_number','Numer kolejki','required|integer|xss_clean');
                $this->form_validation->set_rules('liga','Wybrana liga','required|integer|xss_clean');
                if($this->input->post('year')=='lista')
                    $this->form_validation->set_rules('lyear','Sezon','required|numeric|xss_clean');
                else
                    $this->form_validation->set_rules('iyear','Sezon','required|numeric|xss_clean');
            }
            $this->form_validation->set_rules('gosp[]','Gospodarz meczu','required|integer|xss_clean');
            $this->form_validation->set_rules('gosc[]','Gość meczu','required|integer|xss_clean');
            if($this->input->post('update_fixture'))
                $this->form_validation->set_rules('gid[]','ID meczu','required|integer|xss_clean');
            if(array_filter($ggp) && array_filter($ggc) && count($ggp)==count($ggc))
            {
                $this->form_validation->set_rules('gosp-gol[]','Gole gospodarz','numeric|xss_clean');
                $this->form_validation->set_rules('gosc-gol[]','Gole gość','numeric|xss_clean');
            }
            $this->form_validation->set_rules('godz[]','Godzina meczu','_check_game_time');
            if($this->form_validation->run() == FALSE && $this->input->post('add_fixture'))
                $this->add_fixture();
            elseif($this->form_validation->run() == FALSE && $this->input->post('update_fixture'))
                $this->edit_fixture($this->input->post('fid'));
            else
            {
                $number = count($this->input->post('gosp'));
                $batch_games = array();
                $gosp = $this->input->post('gosp');
                $gosc = $this->input->post('gosc');
                $godz = $this->input->post('godz');
                $data = strtotime($this->input->post('fixt_date'));
                if($this->input->post('add_fixture'))
                {
                    $sezon  = ($this->input->post('year')=='lista') ? $this->input->post('lyear') : $this->input->post('iyear');
                    $liga   = $this->input->post('liga');
                    $kolejka= $this->input->post('fixt_number');
                }
                elseif($this->input->post('update_fixture'))
                {
                    $sezon  = $this->input->post('sid');
                    $liga   = $this->input->post('lid');
                    $kolejka= $this->input->post('fid');
                }
                $gosp_gol   = $this->input->post('gosp-gol');
                $gosc_gol   = $this->input->post('gosc-gol');
                $games_id   = $this->input->post('gid');
                for($i=0;$i<$number;$i++)
                {
                    $played = 0;
                    if(!empty($gosp_gol[$i]) && !empty($gosc_gol[$i]))
                        $played = 1;
                    $match_info = array(
                        'game_team1' => $gosp[$i],
                        'game_team2' => $gosc[$i],
                        'game_league'=> $liga,
                        'game_hour'  => $godz[$i],
                        'game_fixture'  => $kolejka,
                        'game_date'  => $data,
                        'game_season'=> $sezon,
                        'game_played'=> $played
                    );
                    $game_id = $games_id[$i];
                    /*
                     * DOKOŃCZYĆ AKTUALIZACJĘ KOLEJKI
                     */
                    if($this->input->post('add_fixture'))
                        $state = $this->liga->insert_match_info($match_info);
                    elseif($this->input->post('update_fixture'))
                        $state = $this->liga->update_match_info($match_info,$game_id);
                    $this->log->log_event($this->sesja,$state);
                    if($state)
                    {
                        if($gosp[$i]!='' && $gosc[$i]!='')
                        {
                            if($gosp_gol[$i]>$gosc_gol[$i])
                            {
                                $pteam1 = '3';
                                $pteam2 = '0'; 
                            }
                            elseif($gosp_gol[$i]==$gosc_gol[$i])
                            {
                                $pteam1 = '1';
                                $pteam2 = '1';
                            }
                            elseif($gosp_gol[$i]<$gosc_gol[$i])
                            {
                                $pteam1 = '0';
                                $pteam2 = '3';
                            }
                            $match_scores[] = array(
                                'gs_game'=> ($this->input->post('add_fixture') ? $this->db->insert_id() : $game_id),
                                'gs_team'=> $gosp[$i],
                                'gs_goalfor'=> $gosp_gol[$i],
                                'gs_goalaga'=> $gosc_gol[$i],
                                'gs_points' => $pteam1
                            );
                            $match_scores[] = array(
                                'gs_game'=> ($this->input->post('add_fixture') ? $this->db->insert_id() : $game_id),
                                'gs_team'=> $gosc[$i],
                                'gs_goalfor'=> $gosc_gol[$i],
                                'gs_goalaga'=> $gosp_gol[$i],
                                'gs_points' => $pteam2
                            );
                        }
                    }
                    else
                    {
                        $this->elems->load_alert($this->sesja,'error','Dodanie meczu nie powiodło się!',get_back_link());
                        break;
                    }
                    $number = 2*$number;
                    if(count($match_scores)>0)
                    {
                        /*NIESKOŃCZONA PĘTLA NA UPDATE*/
                        if($this->input->post('add_fixture'))
                            $state = $this->liga->insert_scores($match_scores,$number);
                        elseif($this->input->post('update_fixture'))
                            $state = $this->liga->update_scores($match_scores,$number);
                        $this->log->log_event($this->sesja,$state);
                        if($state)
                            if($this->input->post('add_fixture'))
                                $this->elems->load_alert($this->sesja,'success','Poprawnie dodano mecze do bazy danych',anchor('league/add_fixture','Dodaj następną kolejkę',array('class'=>'btn btn-primary')));
                            elseif($this->input->post('update_fixture'))
                                $this->elems->load_alert($this->sesja,'success','Poprawnie zaktualizowano dane meczy',get_back2_link());
                        else
                            if($this->input->post('add_fixture'))
                                $this->elems->load_alert($this->sesja,'error','Wystąpił błąd podczas dodawania wyników meczy!',get_back_link());
                            elseif($this->input->post('update_fixture'))
                                $this->elems->load_alert($this->sesja,'error','Wystąpił błąd podczas aktualizowania wyników meczy!',get_back_link());
                    }
                    else
                        $this->elems->load_alert($this->sesja,'success','Informacje o kolejce ligowej zostały poprawnie dodane do bazy.',anchor('league/add_fixture','Dodaj następną kolejkę',array('class'=>'btn btn-primary')));
                }
            }
        }
        else
            $this->elems->load_alert($this->sesja,'error','Nie masz uprawnień do korzystania z tej strony');
    }
    
    public function edit_game($id)
    {
        if(isset($this->sesja['id']) && $this->sesja['editor']==1 && is_numeric($id))
        {
            $game   = $this->liga->get_game($id);
            $this->log->log_event($this->sesja,$game['stan']);
            if($game['stan'])
            {
                $head['h1']     = 'Edycja meczu: '.$game['wynik']['gosp_name'].' - '.$game['wynik']['gosc_name'];
                $cont['game']   = $game['wynik'];
                $foot['js']     = array('js/league/edit_game.js');
                $this->elems->load_view($this->sesja,'league/edit_game',$cont,$head,$foot);
            }
            else
                $this->elems->load_alert($this->sesja,'error','Nie ma takiego meczu');
        }
        else
            $this->elems->load_alert($this->sesja,'error','Nie masz uprawnień do korzystania z tej strony');
    }
    
    /*
     * @param int $fid - fixture ID
     * @param int $lid - league ID
     * @param int $sid - season
     */
    public function edit_fixture($fid,$lid,$sid)
    {
        if(isset($this->sesja['id']) && $this->sesja['editor']==1 && is_numeric($fid) && is_numeric($lid) && is_numeric($sid))
        {
            $tab['game_fixture']= $fid;
            $tab['league_id']   = $lid;
            $tab['game_season'] = $sid;
            $fixture = $this->liga->get_fixture($tab);
            if($fixture['stan'])
            {
                $head['h1']     = 'Kolejka '.$fixture['wynik']['fixture']['number'].' - '
                        .$fixture['wynik']['fixture']['league_code'].', '
                        .$fixture['wynik']['fixture']['comp_code'].' '
                        .$fixture['wynik']['fixture']['game_season'];
                $this->load->model('Team_model');
                $teams = $this->Team_model->get_teams_by_league($lid);
                if($teams['stan'])
                {
                    $cont['teams']  = $teams['wynik'];
                    $cont['fixture']= $fixture['wynik'];
                    $foot['js']     = array(
                        'js/league/time_select.js',
                        'js/default/datepicker.js'
                    );
                    $this->elems->load_view($this->sesja,'league/edit_fixture',$cont,$head,$foot);
                }
                else
                    $this->elems->load_alert($this->sesja,'error','Brak aktywnych drużyn w bazie');
            }
            else
                $this->elems->load_alert($this->sesja,'error','Nie ma takiej kolejki ligowej');
        }
        else
            $this->elems->load_alert($this->sesja,'error','Nie masz uprawnień do korzystania z tej strony');
    }
    
    public function get_json_events()
    {
        
        $json = json_encode($this->liga->get_events());
        if($json=='')
            $state = TRUE;
        else
            $state = FALSE;
        $this->log->log_event($this->sesja,$state);
        echo $json;
    }
    
    public function get_json_team_players($gospid,$goscid)
    {
        $json = json_encode($this->liga->get_team_players($gospid,$goscid));
        if($json=='')
            $state = TRUE;
        else
            $state = FALSE;
        $this->log->log_event($this->sesja,$state);
        echo $json;
    }
    
    public function update_game()
    {
        if(isset($this->sesja['id']) && $this->sesja['editor']==1 && $this->input->post('edit_game'))
        {
            if($this->input->post('state')==='played')
            {
                $this->load->library('form_validation');
                $this->form_validation->set_error_delimiters('<p class="error">','</p>');
                $this->form_validation->set_rules('state','Status meczu','_check_state');
                $this->form_validation->set_rules('gosp_for','Bramki - gospodarz','required|integer|xss_clean');
                $this->form_validation->set_rules('gosc_for','Bramki - gość','required|integer|xss_clean');
                $this->form_validation->set_rules('gid','ID meczu','_check_game_id');
                $this->form_validation->set_rules('gid','ID ligi','_check_league_id');

                if($this->form_validation->run() == FALSE)
                    $this->edit_game($this->input->post('gid'));
                else
                {
                    $this->liga->set_game_played($this->input->post('gid'));
                    $this->log->log_event($this->sesja,TRUE);
                    if($this->input->post('gosp_for')>$this->input->post('gosc_for'))
                    {
                        $pteam1 = '3';
                        $pteam2 = '0'; 
                    }
                    elseif($this->input->post('gosp_for')==$this->input->post('gosc_for'))
                    {
                        $pteam1 = '1';
                        $pteam2 = '1';
                    }
                    elseif($this->input->post('gosp_for')<$this->input->post('gosc_for'))
                    {
                        $pteam1 = '0';
                        $pteam2 = '3';
                    }
                    $tab = array(
                        array(
                            'gs_game'   => $this->input->post('gid'),
                            'gs_team'   => $this->input->post('t1id'),
                            'gs_goalfor'=> $this->input->post('gosp_for'),
                            'gs_goalaga'=> $this->input->post('gosc_for'),
                            'gs_points' => $pteam1
                        ),
                        array(
                            'gs_game'   => $this->input->post('gid'),
                            'gs_team'   => $this->input->post('t2id'),
                            'gs_goalfor'=> $this->input->post('gosc_for'),
                            'gs_goalaga'=> $this->input->post('gosp_for'),
                            'gs_points' => $pteam2
                        ),
                    );
                    $state = $this->liga->update_game($tab,$gid);
                    $this->log->log_event($this->sesja,$state);
                    if($state)
                        $this->elems->load_alert($this->sesja,'success','Zaktualizowano wynik meczu.',anchor('league/show_league/'.$this->input->post('lid'),'Wróć do widoku meczy', array('class'=>'btn btn-inverse')));
                    else
                        echo $this->db->last_query();
                }
            }
            elseif($this->input->post('state')==='postponed')
            {
                $this->liga->set_game_postponed($this->input->post('gid'));
                $this->elems->load_alert($this->sesja,'success','Ustawiono status: przełożony, dla wybranego meczu.');
            }
        }
        else
            $this->elems->load_alert($this->sesja,'error','Nie masz uprawnień do korzystania z tej strony');
    }
    
    private function _check_state($state)
    {
        $match = array('played','postponed');
        if(in_array($state,$match))
            return TRUE;
        else
            return FALSE;
    }
    
    private function _check_game_id($id)
    {
        if($this->liga->check_game_id($id))
            return TRUE;
        else
            return FALSE;
    }
    
    private function _check_team_id($id)
    {
        $state = $this->liga->check_team_id($id);
        $this->log->log_event($this->sesja,$state);
        if($state)
            return TRUE;
        else
            return FALSE;
    }
    
    private function _check_game_time($game_times)
    {
        $bool = TRUE;
        foreach($game_times as $time)
        {
            if(!preg_match('/\d{2}:\d{2}/',$time))
            {
                $bool = FALSE;
                break;
            }
        }
        if($bool)
            return TRUE;
        else
            return FALSE;
    }
    
    private function _check_array_team_id($teams)
    {
        $bool = TRUE;
        foreach($teams as $team)
        {
            $state = $this->liga->check_team_id($team);
            $this->log->log_event($this->sesja,$state);
            if(!$state)
            {
                $bool = FALSE;
                break;
            }
        }
        if($bool)
            return TRUE;
        else
            return FALSE;
    }
    
    private function _check_league_id($id)
    {
        $state = $this->liga->check_league_id($id);
        $this->log->log_event($this->sesja,$state);
        if($state)
            return TRUE;
        else
            return FALSE;
    }
}